<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroupid">
        <el-input
          v-model="queryParams.name"
          class="icon-search"
          clearable
          placeholder="请输入教育集团名称"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="creatOTA"
          v-hasPermi="['system:post:add']"
          >创建OTA任务</el-button
        >
      </el-col>-->
      <!-- <el-col :span="1.5">
            <el-button
               type="success"
               plain
               icon="Edit"
               :disabled="single"
               @click="handleUpdate"
               v-hasPermi="['system:post:edit']"
            >修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="danger"
               plain
               icon="Delete"
               :disabled="multiple"
               @click="handleDelete"
               v-hasPermi="['system:post:remove']"
            >删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button
               type="warning"
               plain
               icon="Download"
               @click="handleExport"
               v-hasPermi="['system:post:export']"
            >导出</el-button>
         </el-col> -->
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="edGroupList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
      <el-table-column
        label="教育集团编号"
        width="300"
        align="center"
        prop="id"
      />
      <!-- show-overflow-tooltip -->
      <el-table-column
        label="教育集团名称"
        show-overflow-tooltip
        align="center"
        prop="name"
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.name" type="error">
            {{ scope.row?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        show-overflow-tooltip
        align="center"
        prop="photo"
      >
        <template #default="scope">
          <div style="z-index: 10000">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.photo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
              :preview-src-list="srcList"
              show-progress
              :initial-index="0"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        ref="EdgroupRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="教育集团名称" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入教育集团名称"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="limit"
            list-type="picture-card"
            v-model="form.photo"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ota">
import { getFirmwaresList } from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import { mqttOtaUpgrade } from "@/api/system/firmware/ota";
import {
  getEdgroupList,
  getEdgroupById,
  updateEdgroupById,
  createEdgroup,
  deleteEdgroupById
} from "@/api/system/school/edgroup";
const { proxy } = getCurrentInstance();
const limit = ref(1);
const { action_ota, firmware_type } = proxy.useDict(
  "action_ota",
  "firmware_type"
);
const srcList = ref([]);
const options = reactive({
  file: null, // 上传的固件文件
  filename: "firmware", // 默认文件名称
  outputType: "bin", // 默认输出文件类型（例如 .bin 或 .hex）
  previews: {}, // 预览数据（如果需要）
});


// console.log(firmware_type);

const edGroupList = ref([]);
const firmwaresLists = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const gatewayList = ref([]);
const wristbandList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
  },
  rules: {
    name: [{ required: true, message: "教育集团名称不能为空", trigger: "blur" }],
    "edgroup.id": [
      { required: true, message: "教育集团名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);
function rawChange(val) {
  if (!val) {
  }
}

/** 查询教育集团列表 */
function getList() {
  loading.value = true;
  edGroupList.value = [];
  srcList.value = [];
  getEdgroupList(queryParams.value).then((response) => {
    console.log("教育集团列表", response.data);
    edGroupList.value = response.data.data;
    edGroupList.value.forEach((item) => {
      srcList.value.push(item.photo);
    });
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getEdgroupById(id).then((response) => {
    console.log(response);
    form.value = response.data;
    open.value = true;
    title.value = "修改教育集团";
  });
}

// 固件列表
function getFirmwaresLists() {
  getFirmwaresList().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      firmwaresLists.value = data;
    } else {
      firmwaresLists.value = [];
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    edgroup: {
      id: 1,
    },
    name: "", //
    photo: "",
    force: false,
    remain: false,
  };
  proxy.resetForm("EdgroupRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增教育集团";
}

/** OTA任务选择固件 带出固件类型 */
function firmwareChange(value) {
  form.value.firmwareType = value.firmwareType;
  form.value.edgroupid = value.id;
  form.value.full = 0;
  form.value.gw_mac = "";
  form.value.gw_full = 0;
  form.value.wb_mac = "";
  form.value.wb_full = 0;
  form.value.force = false;
  form.value.remain = false;
}

function forceChange(val) {
  if (!val) {
  }
}

function remainChange(val) {
  if (!val) {
  }
}

/** 网关勾选全部 */
function gwFullChange(event, label) {
  // 清空网关
  form.value.gw_mac = "";
  // 取消勾选全部时，初始长期更新设置 并disabled
  if (event === "0") form.value.remain = false;
}

/** 手环网关勾选全部 */
function wbMacChange(event, label) {
  // 清空手环网关
  form.value.wb_mac = "";
  // 取消勾选全部时，初始长期更新设置 并disabled
  if (event === "0") form.value.remain = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["EdgroupRef"].validate((valid) => {
    if (valid) {
      console.log(111, form.value.id);
      if (form.value.id != undefined) {
        console.log("update", form.value);
        updateEdgroupById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("修改失败");
          }
        });
      } else {
        console.log("add", form.value);
        createEdgroup(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("新增失败");
          }
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteEdgroupById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 修改操作 */
function handleEdit(row) {
  const params = {
    taskId: row.id,
    edgroupid: row.edgroupid,
    localPath: row.path,
    force: row.force || false,
  };
  proxy.$modal
    .confirm(`是否现在升级任务编号为 ${row.id} 的任务？`)
    .then(function () {
      return mqttOtaUpgrade(params);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("开始升级");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}

getFirmwaresLists();
getList();
</script>

<style scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
</style>
